#include <iostream>

#include "xlcomm/net/endian.h"
#include "xlcomm/net/tcp_client.h"

using namespace xlcomm;

class TimeClient {
 public:
  TimeClient(net::EventLoop* loop, const net::InetAddress& server_addr)
      : loop_(loop), client_(loop, server_addr, "TimeClient") {
    client_.set_message_callback(
        std::bind(&TimeClient::OnMessage, this, _1, _2, _3));
    client_.set_disconnect_callback(
        std::bind(&TimeClient::OnDisconnect, this, _1));
  }

  void Connect() { client_.Connect(); }

 private:
  void OnMessage(const net::TcpConnectionPtr& conn, net::Buffer* buff,
                 Timestamp recv_time) {
    if (buff->ReadableBytes() >= sizeof(int64_t)) {
      Timestamp now = buff->ReadInt64ToHost();
      std::cout << "receive " << DateTime::Format(now) << " at "
                << DateTime::Format(recv_time) << std::endl;
    } else {
      LOG_INFO << conn->name() << " not enough data";
    }
  }

  void OnDisconnect(const net::TcpConnectionPtr& conn) { loop_->Quit(); }

  net::EventLoop* loop_;
  net::TcpClient client_;
};

int main(int argc, const char* argv[]) {
  // Logger::SetWriteToFile("time_client", true);
  net::EventLoop loop;
  TimeClient client(&loop, net::InetAddress(10002, "127.0.0.1"));
  client.Connect();
  loop.Loop();
  return 0;
}